package com.hbu.housingbrokerug.activities;

import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hub.R;
/**
 * 
 * @author Lubwama Samuel
 *
 */
public class FeedBack extends Activity {
	JSONParser jsonParser = new JSONParser();
	parserFromUrl parser=new parserFromUrl();
	TextView commentTitle,ratting;
    RatingBar houserate;
    private ProgressDialog pDialog;
	EditText userComments;
	EditText userEmail;
	EditText phoneNoOf;
	RatingBar rattingOf;
	TextView interpreteRating;
	String emailInvalid;
	private static final String TAG_SUCCESS = "success";   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.feed_back);
		
		
		userComments = (EditText) findViewById(R.id.commentData);
		userEmail = (EditText) findViewById(R.id.emailData);
		phoneNoOf=(EditText)findViewById(R.id.phoneNo);
		rattingOf = (RatingBar) findViewById(R.id.ratingBar);
		Button sendFeedBackButton = (Button) findViewById(R.id.sendFeedBack);
		interpreteRating=(TextView) findViewById(R.id.interpreteRating);
		
		addListenerOnRatingBar();
		// button click event
		sendFeedBackButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// creating new product in background thread
				new CreateNewProduct().execute();
			}
		});	
		
	}
	
	
	
	
	private void addListenerOnRatingBar() {
		// TODO Auto-generated method stub
		rattingOf = (RatingBar) findViewById(R.id.ratingBar);
		interpreteRating = (TextView) findViewById(R.id.interpreteRating);

		//if rating is changed,
		//display the current rating value in the result (textview) automatically
		rattingOf.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				interpreteRating.setText(String.valueOf(rating));

			}
		});
		
	}


	
	
	


	/**
	 * Background Async Task to Create new product
	 * */
	class CreateNewProduct extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(FeedBack.this);
			pDialog.setMessage("Creating Product..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		
		
	    	protected String doInBackground(String... args) {
	        final Bundle bundle=getIntent().getExtras();
	    	String comment = userComments.getText().toString();
			String email = userEmail.getText().toString();
			String phone = phoneNoOf.getText().toString();
			String getSimNumber="";
			String rattingOfData = String.valueOf(rattingOf.getRating());
			String unit_id=bundle.getString("UNIT_ID");
			
			
			final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(

		            "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
		                    + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
		                    + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
		                    + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
		                    + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
		                    + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$");
			
			
			
			
			
			try{
			TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			 getSimNumber = telemamanger.getSimSerialNumber();
			
			Log.d("Phone Number", telemamanger.getSimSerialNumber());
			}catch(Exception e){
			 getSimNumber="None found";
				Log.e("Error Phone Number", e+"");
			}

			if(EMAIL_ADDRESS_PATTERN.matcher(email).matches()){
				 emailInvalid="false";
			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(parser.getIpOrDomain()+parser.getPostFile(),"POST",parser.getParametersSingleUnitFeedBack(getSimNumber,unit_id, phone, email, comment, rattingOfData));
			
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// successfully created product
					Intent intent = new Intent(getApplicationContext(), SingleUnit.class);
					intent.putExtra("UNIT_ID",bundle.getString("UNIT_ID"));
					intent.putExtra("UNIT_DISTRICT",bundle.getString("UNIT_DISTRICT"));
					intent.putExtra("UNIT_CITY",bundle.getString("UNIT_CITY"));
					intent.putExtra("UNIT_TOWN",bundle.getString("UNIT_TOWN"));
					intent.putExtra("UNIT_VILLAGE",bundle.getString("UNIT_VILLAGE"));
					intent.putExtra("UNIT_LATITUDE",bundle.getString("UNIT_LATITUDE"));
					intent.putExtra("UNIT_LONGITUDE",bundle.getString("UNIT_LONGITUDE"));
					intent.putExtra("UNIT_CATEGORY",bundle.getString("UNIT_CATEGORY"));
					intent.putExtra("UNIT_COST",bundle.getString("UNIT_COST"));
					intent.putExtra("LANDLORD_FIRSTNAME",bundle.getString("LANDLORD_FIRSTNAME"));
					intent.putExtra("LANDLORD_LASTNAME",bundle.getString("LANDLORD_LASTNAME"));
					intent.putExtra("CONTACTS",bundle.getString("CONTACTS"));	
					intent.putExtra("FEEDBACK_STATUS","success");	
					
					startActivity(intent);
					
					// closing this screen
					finish();
				} else {
					// failed to create product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
	    }
		else{
			 emailInvalid="True";
			
		}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
			runOnUiThread(new Runnable() {
				public void run() {
					if(emailInvalid=="True"){
						userEmail = (EditText) findViewById(R.id.emailData);
						userEmail.setText("INVALID EMAIL");
					}
                    
				}
			});
		}

	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.feed_back, menu);
		return true;
	}

}
